package com.terry.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf reader = (ByteBuf)msg;
		try {
//			int length = reader.readableBytes();
//			byte[] r = new byte[length];
//			reader.readBytes(r);
//			System.out.println(new String(r));
//			this.write(ctx);
			printByte(reader);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}
	private void printByte(ByteBuf msg) {
		while(msg.isReadable()) {
			System.out.print(msg.readByte());
		}
	}
	
	private void write(ChannelHandlerContext ctx) {
		String content = "three";
		int length = content.length();
		ByteBuf bb = ctx.alloc().buffer(4 + length);
		bb.writeInt(length);
		bb.writeBytes(content.getBytes());
		String msg = "four";
		int length1 = msg.length();
		
		bb.writeInt(length1);
		bb.writeBytes(msg.getBytes());
		
		ctx.write(bb);
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("exception caught");
		cause.printStackTrace();
	}
	

}
